package com.car.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class phoneRegisterController {
@RequestMapping("/toPhone")
	public String Phone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 电话号
		String phone = request.getParameter("phone");
		// accountSid
		String accountSid = "28d79c2eeea24f838ce0586a64cc09cf";
		String token = "68a7488aefa4472c99b4c9665a33f96a";
		int num = (int) ((Math.random() * 9 + 1) * 100000);// 随机生成6位随机数
		// 发送的短信信息
		String smsContent = "【秋色宜人】尊敬的用户，您的验证码为" + num + "";

		// http 访问 的 地址
		String path = "https://api.miaodiyun.com/20150822/industrySMS/sendSMS";
		// 参数
		String params = "accountSid={accountSid}&smsContent={smsContent}&to={to}&timestamp={time}&sig={sig}&respDataType=JSON";
		//////////////// 一些参数信息
		// to
		String to = phone;
		// time 时间戳
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String timestamp = sdf.format(new Date());
		// String time = DateUtil.getDateContent(new Date());// 获取时间
		// 签名
		String sig = DigestUtils.md5Hex(accountSid + token + timestamp);
		params = params.replace("{accountSid}", accountSid);
		params = params.replace("{smsContent}", smsContent);
		params = params.replace("{to}", to);
		params = params.replace("{time}", timestamp);
		params = params.replace("{sig}", sig);
		try {
			URL url = new URL(path);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("POST");
			// http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			// 设置连接参数
			http.setDoOutput(true);
			http.setDoInput(true);
			http.setConnectTimeout(5000);// 超时时间
			http.setReadTimeout(20000);
			// http.connect(); 读取socket发送的信息 接收信息
			OutputStream os = http.getOutputStream();
			os.write(params.getBytes("UTF-8"));// 发送数据
			os.flush();
			os.close();
			// 获取返回信息
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			System.out.println("返回信息：" + message);

		} catch (Exception e) {

		}
		String ss = num+"";
		return ss;
	}
}
